package com.bsj.power.pls.queue;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bsj.consumerQ.function.HandleRunT;
import com.bsj.consumerQ.method.QueueAndRunT;
import com.bsj.power.common.config.cached.*;
import com.bsj.power.common.config.redis.RedisConstant;
import com.bsj.power.common.config.rocketmq.producer.BaseMqPushUtil;
import com.bsj.power.common.constant.AlarmEnum;
import com.bsj.power.common.constant.MqTopicAndTagConstants;
import com.bsj.power.common.constant.NumericalConstants;
import com.bsj.power.common.def.dto.cardReport.BindCardDTO;
import com.bsj.power.common.def.dto.locationDevice.TagAlarmDetailDTO;
import com.bsj.power.common.def.dto.locationDevice.TagAlarmMsgDTO;
import com.bsj.power.common.def.entity.alarmReport.AlarmReport;
import com.bsj.power.common.def.entity.job.WorkPersonnel;
import com.bsj.power.common.def.entity.locationDevice.LocationDevice;
import com.bsj.power.common.def.entity.log.VideoOpLog;
import com.bsj.power.common.def.entity.personnel.Personnel;
import com.bsj.power.common.def.enums.VideoOpTypeEnum;
import com.bsj.power.common.def.vo.WebSocketMsgVO;
import com.bsj.power.common.mapper.AlarmReportMapper;
import com.bsj.power.common.mapper.VideoOpLogMapper;
import com.bsj.power.common.util.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author LiJiaXin
 * @version 1.0.0
 * @description 标签告警信息队列
 * @time 2024/11/25 16:51
 */
@Slf4j
@Component
public class TagAlarmMsgQueue extends QueueAndRunT<TagAlarmMsgDTO> {

    @Autowired
    private BindCardCached bindCardCached;

    @Autowired
    private PersonnelCached personnelCached;

    @Autowired
    private WorkPersonnelCached workPersonnelCached;

    @Autowired
    private LocationDeviceCached locationDeviceCached;

    @Autowired
    private PathCached pathCached;

    @Autowired
    private BaseMqPushUtil baseMqPushUtil;

    @Autowired
    private RedisCached redisCached;

    @Autowired
    private MsgQueue msgQueue;

    @Resource
    private AlarmReportMapper alarmReportMapper;

    @Autowired
    private VideoOpLogMapper videoOpLogMapper;

    public void start() {
        start("tagAlarmMsgQueue", new HandleRunT<TagAlarmMsgDTO>() {
            @Override
            public void doRun(List<TagAlarmMsgDTO> list) {
                if (CollectionUtils.isEmpty(list)) {
                    return;
                }
                try {
                    for (TagAlarmMsgDTO tagAlarmMsgDTO : list) {
                        //0表示触发开始 1表示触发中 2表示触发结束
                        int status = tagAlarmMsgDTO.getStatus();
                        //0和2以外的不做处理
                        if (status != NumericalConstants.ZERO && status != NumericalConstants.TWO) {
                            continue;
                        }
                        String detail = tagAlarmMsgDTO.getDetail();
                        if (StringUtils.isBlank(detail)) {
                            continue;
                        }
                        TagAlarmDetailDTO tagAlarmDetailDTO = JSONObject.parseObject(detail, TagAlarmDetailDTO.class);
                        if (tagAlarmDetailDTO == null) {
                            continue;
                        }
                        String deviceName = tagAlarmDetailDTO.getTagSn();
                        if (StringUtils.isBlank(deviceName)) {
                            continue;
                        }
                        long timeMs = tagAlarmMsgDTO.getTimeMs();
                        LocationDevice locationDevice = locationDeviceCached.hgetLocationDeviceInfo(deviceName);
                        if (status == NumericalConstants.ZERO) {
                            Integer alarmLevel = pathCached.hgetAlarmLevel(AlarmEnum.ELECTRON_PATH_ALARM.getCode());
                            AlarmReport alarmReport = new AlarmReport();
                            alarmReport.setAlarmType(AlarmEnum.ELECTRON_PATH_ALARM.getCode());
                            alarmReport.setDeviceName(deviceName);
                            alarmReport.setNikeName(locationDevice == null ? "" : locationDevice.getNikeName());
                            alarmReport.setDeviceType(2);
                            alarmReport.setBeginTime(new Date(timeMs));
                            alarmReport.setAlertLevel(alarmLevel);
                            //绑卡信息
                            BindCardDTO bindCardDTO = bindCardCached.hgetBindCardInfo(RedisConstant.BIND_CARD_REDIS_DEVICE_NAME_KEY + deviceName);
                            if (bindCardDTO != null) {
                                Integer personType = 2;
                                String empNo = bindCardDTO.getEmpNo();
                                //负责人员信息
                                Personnel personnel = personnelCached.hgetPersonnelInfo(empNo);
                                if (personnel != null) {
                                    personType = 1;
                                }
                                //作业人员信息
                                WorkPersonnel workPersonnel = workPersonnelCached.getWorkPersonnelInfo(empNo);
                                if (personnel != null || workPersonnel != null) {
                                    alarmReport.setPersonnelId(personnel != null ? personnel.getPersonnelId() : workPersonnel.getWorkPersonnelId());
                                    alarmReport.setPersonnelName(personnel != null ? personnel.getName() : workPersonnel.getName());
                                    alarmReport.setPersonType(personType);
                                }
                            }
                            //缓存开始时间
                            redisCached.set(RedisConstant.ELECTRON_PATH_ALARM_KEY + deviceName, timeMs);
                            //推送给前端
                            WebSocketMsgVO webSocketMsgVO = WebSocketMsgVO.builder()
                                    .msgType(8)
                                    .obj(alarmReport)
                                    .build();
                            baseMqPushUtil.sendTopicBytes(MqTopicAndTagConstants.SYSTEM_WEB_SERVER_CHANGE_TOPIC,
                                    MqTopicAndTagConstants.SYSTEM_WEB_PRODUCT_CHANGE_TAG, JSON.toJSONBytes(webSocketMsgVO));
                        } else if (status == NumericalConstants.TWO) {
                            //保存报警信息
                            VideoOpLog videoOpLog = new VideoOpLog();
                            int type = VideoOpTypeEnum.ELECTRON_PATH_ALARM.getOpType();
                            videoOpLog.setDeviceId(deviceName);
                            videoOpLog.setName(VideoOpTypeEnum.getByValue(type));
                            videoOpLog.setOpUserId(2L);
                            videoOpLog.setOpUserName("admin");
                            videoOpLog.setOpType(type);

                            Long opTime = timeMs;
                            //获取该设备报警开始时间
                            String startTime = redisCached.get(RedisConstant.ELECTRON_PATH_ALARM_KEY + deviceName);
                            if (StringUtils.isNotBlank(startTime)) {
                                opTime = JSON.parseObject(startTime, Long.class);
                                redisCached.del(RedisConstant.ELECTRON_PATH_ALARM_KEY + deviceName);
                            }
                            videoOpLog.setIntervalMillions(timeMs - opTime);
                            videoOpLog.setOpTime(new Date(opTime));
                            videoOpLog.setContent(VideoOpTypeEnum.ELECTRON_PATH_ALARM.getOpTypeValue() + "：" + deviceName);
                            if (locationDevice != null) {
                                videoOpLog.setNickName(locationDevice.getNikeName());
                            }
                            videoOpLogMapper.insert(videoOpLog);
                        }
                    }
                } catch (Exception e) {
                    log.error(ExceptionUtil.getStackStr(e));
                    return;
                }
            }
        });
    }
}
